package drds.binlog.filter;

import com.google.common.base.Function;
import com.google.common.collect.ComputingMap;
import com.google.common.collect.MapMaker;
import drds.binlog.filter.exception.BinlogFilterException;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.Perl5Compiler;

import java.util.Map;

/**
 * 提供{@linkplain Pattern}的lazy get处理
 */
public class Patterns
{

    @SuppressWarnings("deprecation")
    private static Map<String, Pattern> patterns = ComputingMap.makeComputingMap(new MapMaker().softValues(),
            new Function<String, Pattern>()
            {

                public Pattern apply(String pattern)
                {
                    try
                    {
                        PatternCompiler patternCompiler = new Perl5Compiler();
                        return patternCompiler.compile(pattern,
                                Perl5Compiler.CASE_INSENSITIVE_MASK
                                        | Perl5Compiler.READ_ONLY_MASK
                                        | Perl5Compiler.SINGLELINE_MASK);
                    } catch (MalformedPatternException e)
                    {
                        throw new BinlogFilterException(e);
                    }
                }
            });

    public static Pattern getPattern(String pattern)
    {
        return patterns.get(pattern);
    }

    public static void clear()
    {
        patterns.clear();
    }
}
